package com.example.demo.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer implements IWebSocketServer{
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    private String userId;
    @Override
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info(">>>>>>>>>>>>>>开启");
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }

    }

    @Override
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info(">>>>>>>>>>>>>>发送消息");
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        List<String> toUserIds = requestParameterMap.get("toUserId");
        toUserIds.forEach(s->{
            if (webSocketMap.containsKey(s)){
                WebSocketServer webSocketServer = webSocketMap.get(s);
                try {
                    webSocketServer.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                try {
                    this.session.getBasicRemote().sendText("用户："+s+"未登陆");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    @OnClose
    public void onClose() {
        log.info(">>>>>>>>>>>>>>关闭");
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
    }

    @Override
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
